<template>
  <div>
    <h2>用户管理</h2>
    <el-card>
      <div style="margin-bottom: 16px;">
        <el-button type="primary" @click="openAddDialog">新增用户</el-button>
        <el-input v-model="searchKeyword" placeholder="搜索用户名/昵称/手机号/邮箱" style="width: 240px; margin-left: 16px;" clearable @clear="fetchUserList" @keyup.enter="fetchUserList"/>
        <el-button @click="fetchUserList" style="margin-left: 8px;">搜索</el-button>
      </div>
      <el-table :data="userList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="60"/>
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="nickname" label="昵称" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="userType" label="类型" width="90">
          <template #default="scope">
            <el-tag v-if="scope.row.userType === 1">普通用户</el-tag>
            <el-tag v-else-if="scope.row.userType === 2" type="warning">商家</el-tag>
            <el-tag v-else-if="scope.row.userType === 3" type="danger">管理员</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="90">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, jumper"
        @current-change="fetchUserList"
        style="margin-top: 16px; text-align: right;"
      />
    </el-card>

    <!-- 新增/编辑用户弹窗 -->
    <el-dialog v-model="editDialog" :title="editMode === 'add' ? '新增用户' : '编辑用户'" width="400px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="用户名" v-if="editMode === 'add'">
          <el-input v-model="editForm.username" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="editForm.userType" placeholder="请选择">
            <el-option label="普通用户" :value="1" />
            <el-option label="商家" :value="2" />
            <el-option label="管理员" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status" placeholder="请选择">
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码" v-if="editMode === 'add'">
          <el-input v-model="editForm.password" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getUserList, addUser, updateUser, deleteUser } from '../api/user'
import { ElMessage, ElMessageBox } from 'element-plus'

const userList = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const searchKeyword = ref('')

const editDialog = ref(false)
const editMode = ref('add') // 'add' or 'edit'
const editForm = reactive({
  id: null,
  username: '',
  nickname: '',
  phone: '',
  email: '',
  userType: 1,
  status: 1,
  password: ''
})

const fetchUserList = async () => {
  try {
    const res = await getUserList({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    })
    userList.value = res.data || []
    total.value = res.data?.length || 0
  } catch (e) {}
}

const openAddDialog = () => {
  editMode.value = 'add'
  Object.assign(editForm, {
    id: null,
    username: '',
    nickname: '',
    phone: '',
    email: '',
    userType: 1,
    status: 1,
    password: ''
  })
  editDialog.value = true
}

const openEditDialog = (row) => {
  editMode.value = 'edit'
  Object.assign(editForm, row)
  editForm.password = ''
  editDialog.value = true
}

const handleSaveUser = async () => {
  try {
    if (editMode.value === 'add') {
      await addUser(editForm)
      ElMessage.success('添加成功')
    } else {
      await updateUser(editForm.id, editForm)
      ElMessage.success('更新成功')
    }
    editDialog.value = false
    fetchUserList()
  } catch (e) {}
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    await deleteUser(row.id)
    ElMessage.success('删除成功')
    fetchUserList()
  }).catch(() => {})
}

onMounted(() => {
  fetchUserList()
})
</script>